package com.llb666.java.thread.futuretask.demo;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author llb
 */
@Slf4j
public class FutureTaskDemo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 首先我们创建了一个线程池
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d").build();
        ExecutorService executor = new ThreadPoolExecutor(3, 3,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024),
                namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        // futureTask 我们叫做线程任务，构造器的入参是 Callable
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String> () {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                // 返回一句话
                return "我是子线程"+Thread.currentThread().getName();
            }
        });
        // 把任务提交到线程池中，线程池会分配线程帮我们执行任务
        executor.submit(futureTask);
        // 得到任务执行的结果
        String result = (String) futureTask.get();
        log.info("result is {}",result);
    }
}
